<?php

namespace App\Models;

use App\Http\Controllers\QrCodeController;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * 用户微信信息
 * Class ArticleTypeModel
 * @package app\common\model
 */
class UserInfo extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = null;

    public $table = 'user_info';

    public function getTable()
    {
        return $this->table;
    }

    /*关联微信账号*/
    public function conWechat()
    {
        return $this->hasOne(UserWechatInfo::class, 'id', 'wechat_id');
    }


    /*关联图书馆账号*/
    public function conLibrary()
    {
        return $this->hasOne(UserLibraryInfo::class, 'id', 'account_id');
    }

    /*关联用户预约申请记录*/
    public function conReservation()
    {
        //return $this->hasMany(ReservationApply::class, 'user_id', 'id');
    }

    /**
     * 根据用户id  获取微信信息
     * $param field
     */
    public static function getWechatField($user_id, $field)
    {
        $wechat_id = self::where('id', $user_id)->value('wechat_id');
        return UserWechatInfo::where('id', $wechat_id)->value($field);
    }
    /**
     * 根据用户id  获取微信信息
     * $param field
     */
    public function getUserInfoByWechatId($wechat_id, $field = null)
    {
        $res = $this->where('wechat_id', $wechat_id)->first();
        if ($res && $field && !empty($res[$field])) {
            return $res[$field];
        }
        return $res;
    }


    /**
     * 判断用户是否存在
     * @param user_guid 用户guid
     */
    public function getUserInfo($user_guid)
    {
        $res = $this->where('token', $user_guid)->first();
        if (empty($res)) {
            return false;
        }

        return $res;
    }

    /**
     * 根据用户id，获取微信信息
     * @param user_guid 用户guid
     */
    public function getWechatInfo($user_guid)
    {
        $wechat_id = $this->where('token', $user_guid)->value('wechat_id');
        if (empty($wechat_id)) {
            return false;
        }
        $wechat_info = UserWechatInfo::select('nickname', 'head_img', 'tel')->where('id', $wechat_id)->first();
        return $wechat_info ? $wechat_info->toArray() : null;
    }
    /**
     * 根据用户id，获取读者证号信息
     * @param user_guid 用户guid
     */
    public function getAccountInfo($user_guid)
    {
        $account_id = $this->where('token', $user_guid)->value('account_id');
        if (empty($account_id)) {
            return false;
        }

        $account_info = UserLibraryInfo::select('account')->where('id', $account_id)->first();
        return $account_info ? $account_info->toArray() : null;
    }

    /**
     * 获取用户guid  根据关键字
     * @param keywords  微信昵称检索
     */
    public function getUserGuidByKeywords($keywords)
    {
        $wechat_id = UserWechatInfo::where('nickname', 'like', $keywords . '%')->value('id');
        if (empty($wechat_id)) {
            return false;
        }
        $user_guid = $this->where('wechat_id', $wechat_id)->value('token');
        return $user_guid;
    }



    /**关联书籍信息 */
    public function conBookRead()
    {
        //  return $this->hasMany(AudioBookRead::class, 'user_id', 'id');
    }

    /**
     * 根据user_id 获取读者证号id
     */
    public function getAccountId($user_id)
    {
        $account_id = $this->where('id', $user_id)->value('account_id');
        if (empty($account_id)) {
            return false; //未绑定
        }
        return $account_id;
    }
    /**
     * 根据account_id 获取用户id
     */
    public function getUserIdByAccount($account_id)
    {
        $id = $this->where('account_id', $account_id)->value('id');
        if (empty($id)) {
            return false; //未绑定
        }
        return $id;
    }
    /**
     * 获取用户随机编号
     */
    public function getUserRandomSerialNumber()
    {
        $i = 10;
        while ($i) {
            $serial_number = 'U' . get_rnd_number(10);
            //判断qr_code是否重复
            $qr_code_exist = $this->where('serial_number', $serial_number)->first();
            if ($qr_code_exist) {
                $i--;
            } else {
                return $serial_number;
            }
        }
        return false;
    }

    /**
     * 读者证号绑定在用户信息上
     */
    public function setAccountBindUserInfo($account_id, $wechat_id = null)
    {
        $user_info = $this->where('account_id', $account_id)->first();

        if (empty($user_info)) {
            $this->account_id = $account_id;
            $this->token = get_guid();

            $qrCodeObj = new QrCodeController();
            $qr_code = $qrCodeObj->getQrCode('user_info');

            $this->qr_code = $qr_code;
            $this->qr_url = $qrCodeObj->setQr($qr_code, true);

            if ($wechat_id)  $this->wechat_id = $wechat_id;

            $this->save();
            $token = $this->token;
            $id = $this->id;
        } else {
            if ($wechat_id && $user_info->wechat_id != $wechat_id) {
                $user_info->wechat_id = $wechat_id;
                $user_info->save();
            }

            $token = $user_info->token;
            $id = $user_info->id;
        }

        return ['token' => $token, 'id' => $id];
    }

    /**
     * 用户列表
     * @param limit 限制条数 默认为 10
     * @param keywords 检索内容
     * @param is_volunteer 是否是志愿者 0全部  1 是  2 否
     * @param is_violate 是否违规 0全部  1 是  2 否
     * @param sort 排序方式   1 默认排序（默认）  2 积分倒序
     */
    public function lists($keywords, $is_volunteer, $is_violate, $sort = 1, $limit = 10)
    {
        $sort = $sort == 2 ? 'score' : 'create_time';

        $res = $this->from('user_info as u')
            ->select('u.id', 'u.account_id', 'l.account', 'l.username', 'l.sex', 'l.card', 'l.tel', 'l.score', 'u.create_time', 'u.is_volunteer', 'u.activity_violate_num', 'u.reservation_violate_num', 'w.nickname', 'w.head_img')
            ->leftjoin('user_account_lib as l', 'l.id', '=', 'u.account_id')
            ->leftjoin('user_wechat_info as w', 'w.id', '=', 'u.wechat_id')
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('l.username', 'like', "%$keywords%")
                        ->Orwhere('l.account', 'like', "%$keywords%")
                        ->Orwhere('l.card', 'like', "%$keywords%")
                        ->Orwhere('l.tel', 'like', "%$keywords%")
                        ->Orwhere('w.nickname', 'like', "%$keywords%");
                }
            })
            ->where(function ($query) use ($is_volunteer) {
                if ($is_volunteer) {
                    $query->where('l.is_volunteer', $is_volunteer);
                }
            })
            ->where(function ($query) use ($is_violate) {
                if ($is_violate == 1) {
                    $query->where('u.activity_violate_num', '>', 0)->Orwhere('u.reservation_violate_num', '>', 0);
                } elseif ($is_violate == 2) {
                    $query->where('u.activity_violate_num', 0)->where('u.reservation_violate_num', 0);
                }
            })
            ->orderByDesc($sort)
            ->paginate($limit)
            ->toArray();

        return $res;
    }


    /**
     * 获取注册人数（绑定读者证人数）
     * @param $start_time 开始时间
     * @param $end_time 结束时间
     * @param $type 1 注册人数  2 绑定读者证人数
     */
    public function getUserNumber($type = 1, $start_time = null, $end_time = null)
    {
        $number = $this->where(function ($query) use ($type, $start_time, $end_time) {
            if ($type == 2) {
                $query->whereNotNull('account_id');
            }
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        })->count();
        return $number;
    }


    /**
     * 注册人数统计(折线图)
     * @param start_time  开始时间
     * @param end_time  结束时间
     */
    public function registerStatistics($start_time = null, $end_time = null)
    {
        if (date('Y-m-d', strtotime($start_time)) == date('Y-m-d', strtotime($end_time))) {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m-%d %H') as times"), DB::raw("count(id) as number")];
        } else {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m-%d') as times"), DB::raw("count(id) as number")];
        }

        $res = $this->select($field)->where(function ($query) use ($start_time, $end_time) {
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        })->orderBy('times')
            ->groupBy('times')
            ->get()->toArray();

        return $res;
    }



    /**
     * 清空违规次数
     * @param user_id 读者证id
     * @param node  0 全部清空  1 活动 2 预约
     */
    public function clearViolate($user_id, $node = 0)
    {
        if ($node == 1) {
            $saveWhere = ['activity_violate_num' => 0];
        } elseif ($node == 2) {
            $saveWhere = ['reservation_violate_num' => 0];
        } else {
            $saveWhere = ['activity_violate_num' => 0, 'reservation_violate_num' => 0];
        }
        return $this->where('id', $user_id)->update($saveWhere);
    }



    // 生成实例
    public static function getInstance()
    {
        return new self;
    }
}
